package com.liangli.thread.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.liangli.thread.entity.Amazon;
import com.liangli.thread.service.IAmazonService;
import com.liangli.thread.taskasyn.TestAsyncDemo1;
import com.liangli.thread.utils.ExcelReadUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

/**
 * @Author: liangli
 * Date: 2021/10/9 18:43
 * Description:
 */
@RestController
@RequestMapping("/amazon")
public class AmazonController {

    static final Logger log = Logger.getLogger(AmazonController.class);

    @Resource
    IAmazonService amazonService;

    @RequestMapping("/addBatchForThread")
    public String addBatchForThread() {
        //读取amazon.xlsx信息
        String fileName = "E:\\正和创兴\\amazon333.xlsx";
        log.info("fileName-------------"+fileName);
        SaveAmazon saveAmazon = new SaveAmazon();
        //读取excel数据
        AnalysisEventListener<Amazon> amazonListener = ExcelReadUtils.getListener(saveAmazon.batchInsert(), 100);
        EasyExcel.read(fileName, Amazon.class, amazonListener).sheet().doRead();

        List<Amazon> amazonAll = saveAmazon.amazonAll;
        List<Amazon> amazonBatch = new ArrayList<>();

        //遍历数据异步调线程写入数据库
        for (Amazon amazon : amazonAll) {
            amazon.setCreateUserId(0L);
            amazon.setCreateTime(new Date());
            amazonBatch.add(amazon);
            if (amazonBatch.size() >= 100) {
                amazonService.addBatchExecutor(amazonBatch);
                amazonBatch = new ArrayList<>();
            }
        }
        if (amazonBatch.size() > 0) {
            System.out.println(amazonBatch.size());
            amazonService.addBatchExecutor(amazonBatch);
        }
        return "ok";
    }

}

class SaveAmazon {
    List<Amazon> amazonAll = new ArrayList<>();
    public Consumer<List<Amazon>> batchInsert() {
        return amazonList -> {
            amazonAll.addAll(amazonList);
//            System.out.println(System.currentTimeMillis()+"读取数据到amazonAll----------------"+amazonAll.size());
        };
    }
}
